import axios from 'axios'
import {Message} from 'element-ui'
import QS from 'qs'
const http = axios.create({
  baseURL: 'http://127.0.0.1:3000/',
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
  // request timeout
})

// 设置 post、put 默认 Content-Type
http.defaults.headers.post['Content-Type'] = 'application/json'
http.defaults.headers.put['Content-Type'] = 'application/json'

// request interceptor 请求拦截(请求发出前处理请求)
http.interceptors.request.use(
  config => {
    // do something before request is sent
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor 响应拦截器（处理响应数据）
http.interceptors.response.use(
  response => {
    const res = response.data
    const ressuc = res.success
    // 后端返回成功失败是用 success 的true 和 false 判断，所以在这里就获取 response.data 的 success
    if (ressuc) {
      console.log('response', response)
      return res
    } else {
      Message({
        message: res.message || 'error',
        type: 'error',
        duration: 5 * 1000
      })
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export function get (url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    })
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err.data)
      })
  })
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post (url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, QS.stringify(params))
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err.data)
      })
  })
}
